package cn.sunxyz.jdbc;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by yangrd on 2017/5/31.
 */
public class GeneratedKeys {


    private static final Logger logger = LoggerFactory.getLogger(GeneratedKeys.class);
    Connection conn = null;
    PreparedStatement st = null;
    ResultSet rs = null;

    @Before
    public void before() throws Exception {
        //获取一个数据库连接
        conn = JdbcUtils.getConnection();
        logger.debug("connection : {}", conn);
    }

    @After
    public void after() throws Exception {
        logger.debug("release : {} {} {}", conn, st, rs);
        JdbcUtils.release(conn, st, rs);
    }

    @Test
    public void getGeneratedKeys(){
        try{
            conn = JdbcUtils.getConnection();
            String sql = "insert into test1(name) values(?)";
            st = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            st.setString(1, "aaa");
            st.executeUpdate();
            //获取数据库自动生成的主键
            rs = st.getGeneratedKeys();
            if(rs.next()){
                System.out.println(rs.getInt(1));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
